package com.shop.cloud.controller.system;

import io.swagger.annotations.ApiOperation;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.domain.hongfu.Log;
import com.shop.cloud.domain.system.SysPosition;
import com.shop.cloud.domain.system.SysRole;
import com.shop.cloud.domain.system.SysUser;
import com.shop.cloud.domain.system.SysUserRole;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.MagicPermission;
import com.shop.cloud.model.request.AddSysPositionRequest;
import com.shop.cloud.model.request.AddSysRoleRequest;
import com.shop.cloud.model.request.DeleteSysPositionRequest;
import com.shop.cloud.model.request.DeleteSysRoleRequest;
import com.shop.cloud.model.request.EditSysPositionRequest;
import com.shop.cloud.model.request.EditSysRoleRequest;
import com.shop.cloud.model.request.GetSysPositionInfoRequest;
import com.shop.cloud.model.request.GetSysPositionListRequest;
import com.shop.cloud.model.request.GetSysRoleListRequest;
import com.shop.cloud.model.response.AddSysPositionResponse;
import com.shop.cloud.model.response.AddSysRoleResponse;
import com.shop.cloud.model.response.EditSysPositionResponse;
import com.shop.cloud.model.response.EditSysRoleResponse;
import com.shop.cloud.model.response.GetSysPositionListResponse;
import com.shop.cloud.model.response.GetSysRoleListResponse;
import com.shop.cloud.model.response.ObjectDataResponse;
import com.shop.cloud.service.system.IRoleResourceService;
import com.shop.cloud.service.system.ISysPositionService;
import com.shop.cloud.service.system.ISysRoleService;
import com.shop.cloud.service.system.ISysUserRoleService;
import com.shop.cloud.service.system.ISysUserService;
import com.shop.cloud.util.DateTimeUtil;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Page;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

@RestController
@RequestMapping(value = "position")
public class SysPositionController extends BaseController {

	private static final Logger logger=Logger.getLogger(SysPositionController.class);
	
	@Autowired
	private ISysPositionService sysPositionService;
	
	@Autowired
	private ISysRoleService sysRoleService;
	
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	
//	@MagicPermission
//	@RequestMapping(value = "updatePosition", method = RequestMethod.POST)
//	@ResponseBody
//	public Response updatePosition(HttpServletRequest request,boolean isAdd,SysPosition sysPosition) {
//		if(isAdd){
//			sysPositionService.insert(sysPosition);
//		}else{
//			sysPositionService.update(sysPosition);
//		}
//		return ResponseUtil.ok();
//	}
//	
//	
//	@MagicPermission
//	@RequestMapping(value = "findUserRole", method = RequestMethod.POST)
//	@ResponseBody
//	public Response findUserRole(Long userId,HttpServletRequest request){
//		Map<String, Object> params=getPageMap(request);
//		List<SysRole> datas=sysRoleService.find(params);
//		List<String> roleIds=sysRoleService.findUserRole(userId);
//		List<Map<String, Object>> dataList=new ArrayList<Map<String,Object>>();
//		for (int i = 0; i < datas.size(); i++) {
//			SysRole role=datas.get(i);
//			Map<String, Object> dataMap=new HashMap<String, Object>();
//			dataMap.put("id", role.getId());
//			boolean hasValue=false;
//			for (String roleId : roleIds) {
//				if(roleId.equals(role.getId())){
//					hasValue=true;
//				}
//			}
//			if (hasValue) {
//				dataMap.put("check", true);
//			} else {
//				dataMap.put("check", false);
//			}
//			dataMap.put("name", role.getName());
//			dataMap.put("createUser", role.getCreateUser());
//			dataList.add(dataMap);
//		}
//		return ResponseUtil.ok(dataList);
//	}
//	
//	@MagicPermission
//	@RequestMapping(value = "find", method = RequestMethod.POST)
//	@ResponseBody
//	public Response find(@CurrentUserId Long userId,HttpServletRequest request){
//		Map<String, Object> params=getPageMap(request);
//		Page<SysRole> datas=sysRoleService.page(params);
//		return ResponseUtil.ok(datas);
//	}
	
//	@ApiOperation(value = "查询日志" , notes="查询日志")
//	@RequestMapping(value = "queryList", method = {RequestMethod.POST}  )
//	@ResponseBody
//	public ObjectDataResponse<Page<SysPosition>> queryList(@CurrentUserId Long userId,@RequestBody SysPosition sysPosition){
//		logService.addLog(userId, 0, "查询日志");
//		Page<Log> datas=logService.pageLog(log);
//		return new ObjectDataResponse<Page<SysPosition>>(datas);
//	}
	
	
	
//	@MagicPermission
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Response list(HttpServletRequest request, HttpServletResponse response, @RequestBody GetSysPositionListRequest sysPositionListRequest){
		Map<String, Object> map = new HashMap<String, Object>();
		List<GetSysPositionListResponse> datas = new ArrayList<GetSysPositionListResponse>(); 
		GetSysPositionListResponse data = null;
		List<SysPosition> sysPositionList = null;
		SysPosition sysPosition = null;
		SysRole sysRole = null;
		Map<String, Object> params = null;
		int i = 0;
		
		params = new HashMap<String, Object>();
		if(!(sysPositionListRequest.getRole() == null || sysPositionListRequest.getRole().equals(""))) {
			params.put("roleId", sysPositionListRequest.getRole());
		}
		if(!(sysPositionListRequest.getPosition() == null || sysPositionListRequest.getPosition().equals(""))) {
			params.put("id", sysPositionListRequest.getPosition());
		}
		if(!(sysPositionListRequest.getStart_time() == null || sysPositionListRequest.getStart_time().equals(""))) {
			params.put("startTime", sysPositionListRequest.getStart_time());
		}
		if(!(sysPositionListRequest.getEnd_time() == null || sysPositionListRequest.getEnd_time().equals(""))) {
			params.put("endTime", sysPositionListRequest.getEnd_time());
		}
		if(!(sysPositionListRequest.getKey() == null || sysPositionListRequest.getKey().equals(""))) {
			params.put("keyword", sysPositionListRequest.getKey());
		}
		//分页
		if(!(sysPositionListRequest.getPageIndex_() == null || sysPositionListRequest.getPageIndex_().equals(""))){
			params.put("limitStart", (sysPositionListRequest.getPageIndex_()-1)*sysPositionListRequest.getPageSize_());
		}
		if(!(sysPositionListRequest.getPageSize_() == null || sysPositionListRequest.getPageSize_().equals(""))){
			params.put("limitEnd", sysPositionListRequest.getPageSize_());
		}
		if(sysPositionListRequest.getAuthorityNow()!=null){
			
			if(sysPositionListRequest.getAuthorityNow() == 2){
				params.put("authorityNow", sysPositionListRequest.getAuthorityNow());
				params.put("positionIds", sysPositionListRequest.getPositionIds());
	        
	        }
		}
		
		 
		 
		long count = sysPositionService.count(params);
		sysPositionList = sysPositionService.find(params);
		for(i = 0 ; i < sysPositionList.size() ; i++) {
			data = new GetSysPositionListResponse();
			sysPosition = sysPositionList.get(i);
			params = new HashMap<String, Object>();
			params.put("id", sysPosition.getRoleId());
			sysRole = sysRoleService.findOne(params);
			if(sysRole != null) {
				data.setRoleName(sysRole.getName());
			} else {
				data.setRoleName("");
			}
			data.setId(sysPosition.getId());
			data.setRoleId(sysPosition.getRoleId());
			data.setCreate_time(sysPosition.getCreateDate());
			data.setName(sysPosition.getName());
			datas.add(data);
		}
		map.put("data", datas);
		map.put("pageCount", count);
		return ResponseUtil.ok(map);
	}
	
//	@MagicPermission
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public Response update(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody EditSysPositionRequest editSysPositionRequest){
		EditSysPositionResponse editSysPositionResponse = new EditSysPositionResponse();
		SysPosition sysPosition = null;
		SysRole sysRole = null;
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		Long id = 0L;
		Long roleId = 0L;
		
		if(editSysPositionRequest.getId().equals("") ||
		   editSysPositionRequest.getRoleId().equals("") ||
		   editSysPositionRequest.getName().equals("")) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "所有项都必填");
		}
		
		id = Long.parseLong(editSysPositionRequest.getId());
		roleId = Long.parseLong(editSysPositionRequest.getRoleId());
		
		params = new HashMap<String, Object>();
		params.put("eqname", editSysPositionRequest.getName());
		params.put("roleId", editSysPositionRequest.getRoleId());
		sysPosition = sysPositionService.findOne(params);
		if(sysPosition != null) {
			if(sysPosition.getId() != id) {
				return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "名称已存在");
			}
		}
		
		params = new HashMap<String, Object>();
		params.put("id", id);
		sysPosition = sysPositionService.findOne(params);
		if(sysPosition == null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "id不存在");
		}
		
		params = new HashMap<String, Object>();
		params.put("id", roleId);
		sysRole = sysRoleService.findOne(params);
		if(sysRole == null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "不存在此角色类型");
		}
		
		sysPosition.setRoleId(roleId);
		sysPosition.setName(editSysPositionRequest.getName());
		sysPosition.setUpdateDate(currentTime);
		sysPosition.setUpdateUser(userId);
		
		sysPositionService.update(sysPosition);
		
		return ResponseUtil.ok(editSysPositionResponse);
	}
//	
//	@MagicPermission
	@RequestMapping(value = "insertTwo")
	@ResponseBody
	public Response insertTwo(String removeResourceIds,String insertResourceIds,String roleId){
		//sysPositionService.insertTwo(insertResourceIds,roleId);
		return ResponseUtil.ok();
	}

	
//	@MagicPermission
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Response add(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody AddSysPositionRequest addSysPositionRequest){
		AddSysPositionResponse addSysPositionResponse = new AddSysPositionResponse();
		SysPosition sysPosition = null;
		SysRole sysRole = null;
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		Long roleId = 0L;
		
		if(addSysPositionRequest.getRoleId().equals("") ||
		   addSysPositionRequest.getName().equals("")) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "所有项都必填");
		}
		
		roleId = Long.parseLong(addSysPositionRequest.getRoleId());
		
		if(roleId <= 0) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "不存在此角色类型");
		}
		
		params = new HashMap<String, Object>();
		params.put("id", roleId);
		sysRole = sysRoleService.findOne(params);
		if(sysRole == null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "不存在此角色类型");
		}
		
		params = new HashMap<String, Object>();
		params.put("roleId", roleId);
		params.put("name", addSysPositionRequest.getName());
		sysPosition = sysPositionService.findOne(params);
		if(sysPosition != null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "已存在此名称");
		}
		
		sysPosition = new SysPosition();
		sysPosition.setRoleId(roleId);
		sysPosition.setName(addSysPositionRequest.getName());
		sysPosition.setRemark(addSysPositionRequest.getName());
		sysPosition.setCreateUser(userId);
		sysPosition.setUpdateUser(userId);
		sysPosition.setCreateDate(currentTime);
		sysPosition.setUpdateDate(currentTime);
		if(!sysPositionService.insert(sysPosition)) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "插入失败");
		}
		
		return ResponseUtil.ok(addSysPositionResponse);
	}
//
// 	@MagicPermission
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Response delete(@CurrentUserId Long userId,HttpServletRequest request, HttpServletResponse response, @RequestBody DeleteSysPositionRequest deleteSysPositionRequest){
		// 缺少对角色职位的使用判断
		HashMap<String, Object> param= new HashMap<String, Object>();
		param.put("id", deleteSysPositionRequest.getId());
		
		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setPositionId(new Long(deleteSysPositionRequest.getId()));
		List<SysUserRole> sysUserRolelist = sysUserRoleService.find(sysUserRole);
		if(sysUserRolelist.size()>0){
			return ResponseUtil.error("有职位下 有用户正在使用此类型，无法删除！");
		}
		
		//得到单条职位信息
//		SysPosition r = sysPositionService.find(param).get(0);
		
		
//		Map<String,Object> map = new HashMap<String,Object>();
//		map.put("roleId", r.getRoleId());
//		Long roleId = r.getRoleId();
//		System.out.println(sysRoleService.findRole(roleId).size());
//		if(sysRoleService.findRole(r.getRoleId()).size()>0){
//			return ResponseUtil.error("有账户正在使用此角色类型，无法删除！");
//		}else{
//			//sysRoleService.removeUserRole(map);
//			//roleResourceService.remove(map);
//			
//		}
		sysPositionService.remove(param);
		return ResponseUtil.ok();
	}
	
// 	@MagicPermission
	@RequestMapping(value = "info", method = RequestMethod.POST)
	@ResponseBody
	public Response info(@CurrentUserId Long userId,HttpServletRequest request, HttpServletResponse response, @RequestBody GetSysPositionInfoRequest getSysPositionInfoRequest){
		HashMap<String, Object> param= new HashMap<String, Object>();
		param.put("id", getSysPositionInfoRequest.getId());
		SysPosition r = sysPositionService.findOne(param);
		return ResponseUtil.ok(r);
	}

}